<template>
  <!--订单详情-->
  <div class="order-box">
    <el-card style="width: 80%">
      <el-row class="flex-center">
        <h3>确认下单</h3>
      </el-row>
      <el-button style="margin-bottom: 12px" class="back-btn" type="primary" @click="goback">返回</el-button>
      <el-row>
        <el-row>
          <div class="address-container" style="margin-bottom: 20px">
            <el-table
              :border="true"
              ref="multipleTable"
              :data="addressList"
              tooltip-effect="dark"
              style="width: 100%"
            >
              <el-table-column prop="radio" align="center" width="55" label="选择">
                <template v-slot="{ row, $index }">
                  <el-radio
                    :label="$index"
                    v-model="selectedAddressIndex"
                    @change="addressChange($index)"
                  ></el-radio>
                </template>
              </el-table-column>
              <el-table-column align="center" label="收货人" prop="recipient_name" width="120"></el-table-column>
              <el-table-column align="center" prop="recipient_phone" label="收货人电话" width="120"></el-table-column>
              <el-table-column align="center" prop="address" label="收货地址"></el-table-column>

              <el-table-column align="center" width="120" prop="is_default" label="默认地址">
                <template v-slot="{ row }">
                  <el-tag style="cursor: pointer" type="success" v-if="row.is_default">默认</el-tag>
                  <el-tag style="cursor: pointer" title="点击修改为默认地址" type="primary" v-else>否</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-row>
        <div class="address-container">
          <el-table
            :border="true"
            ref="multipleTable"
            :data="cartList"
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column align="center" label="商品主图" prop="pictures" width="120">
              <template v-slot="{ row }">
                <img
                  @click="gotoDetail(row)"
                  :src="JSON.parse(row.pictures)[0]"
                  alt
                  style="width: 80px; height: auto; cursor: pointer"
                />
              </template>
            </el-table-column>
            <el-table-column align="center" label="商品名称" prop="product_name" width="120"></el-table-column>
            <el-table-column align="center" prop="category_name" label="商品分类" width="120"></el-table-column>
            <el-table-column align="center" prop="product_description" label="商品描述"></el-table-column>
            <el-table-column align="center" prop="stock" label="库存(件)" width="120"></el-table-column>

            <el-table-column align="center" width="160" prop="quantity" label="商品数量"></el-table-column>
            <el-table-column align="center" prop="price" label="价格(元)"></el-table-column>
            <el-table-column align="center" prop="price" label="金额(元)">
              <template v-slot="{ row }">
                {{
                parseFloat(row.price * row.quantity).toFixed(2)
                }}
              </template>
            </el-table-column>
          </el-table>
          <div class="total-price">
            <div class="total">
              总价：
              <span class="price">{{ total }}</span> 元
            </div>
            <el-button type="primary" @click="toPay">支付</el-button>
          </div>
        </div>
      </el-row>
    </el-card>
    <!-- 弹框 -->
    <AddDialog
      :storeData="storeForm"
      :title="title"
      v-if="addVisible"
      :visible.sync="addVisible"
      @confirm="addStoreConfirm"
    ></AddDialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import { generateTextAvatar } from "@/utils/generateTextAvatar";
import {
  getAllAddressByUserId,
  getAllCartsByUserId,
  addOrders,
  getInfo,
  updateInfo,
  updateOrders,
  addOrderdetailsByList,
  updateProducts,
  updateCart,
  deleteCart,
} from "@/api/user";
import AddDialog from "./AddDialog.vue";
import { status } from "nprogress";
export default {
  components: {
    AddDialog,
  },
  props: {
    cartList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      total: 0,
      addressList: [],
      selectedAddressIndex: -1, // 新增变量来存储选中的地址索引
      selectAddressInfo: null,
      userInfo: {},
      addVisible: false,
      title: "支付",
      storeForm: {},
    };
  },
  computed: {
    ...mapState("user", ["token"]),
    ...mapGetters(["sidebar", "avatar", "name"]),
  },
  mounted() {
    this.getTotal();
    this.getAllAddressByUserId();
    this.getInfo();
  },
  methods: {
    async getInfo() {
      const { data: res } = await getInfo(+this.token);
      console.log("获取用户信息成功", res);
      this.userInfo = res || {};
    },
    addressChange(index) {
      this.selectedAddressIndex = index;
      this.addressList.forEach((item, i) => {
        item.radio = i === index;
        if (i === index) {
          this.selectAddressInfo = item;
        }
      });
    },
    async getAllAddressByUserId() {
      if (!this.token) {
        this.$message.warning("请先登录！");
        return this.$router.push("/login");
      }
      const { data: res } = await getAllAddressByUserId(+this.token);

      this.addressList = res || [];
      this.addressList.forEach((item, index) => {
        this.$set(item, "radio", false);
        if (item.is_default) {
          this.$set(item, "radio", true);
          this.selectedAddressIndex = index;
          this.selectAddressInfo = item;
        }
      });
      console.log(this.addressList);
    },
    goback() {
      this.$emit("goback");
    },
    getTotal() {
      this.total = 0;
      for (let i = 0; i < this.cartList.length; i++) {
        this.total += this.cartList[i].quantity * this.cartList[i].price;
      }
      this.total = parseFloat(this.total).toFixed(2);
    },
    gotoDetail(row) {
      this.productInfo = row;
    },
    async handleQuantityChange(val, row) {
      const params = {
        cart_id: row.cart_id,
        quantity: +val,
      };
      const res = await updateCart(params);
      if (res.status === 0) {
        this.$message({
          type: "success",
          message: "修改成功",
        });
        this.getAllCartsByUserId();
      } else {
        this.$message.error("修改失败！");
      }
    },
    async toPay() {
      if (!this.selectAddressInfo?.address_id) {
        this.$message.warning("请前往添加收货地址,1秒后自动跳转");
        setTimeout(() => {
          this.$router.push({
            name: "home",
            query: {
              activeComIndex: "AddressIndex",
            },
          });
          //刷新页面
          this.$router.go(0);
        }, 1000);

        return;
      }

      if (this.total > this.userInfo.money) {
        this.$message.warning("余额不足，请先充值,1秒后自动跳转充值页");

        setTimeout(() => {
          this.$router.push({
            name: "home",
            query: {
              activeComIndex: "MoneyIndex",
            },
          });
          //刷新页面
          this.$router.go(0);
        }, 1000);
        return;
      }
      const params = {
        user_id: +this.token,
        total_amount: +this.total,
        address_id: this.selectAddressInfo.address_id,
        status: 1, //未支付
      };
      const res = await addOrders(params);
      console.log("添加订单成功", res);
      if (res.status === 0) {
        const list = this.cartList.map((item) => {
          item.order_id = res.data.order_id;
          delete item.created_at;
          return item;
        });
        console.log("订单详情", list);
        //批量添加订单详情
        const detailRes = await addOrderdetailsByList(list);
        //删除购物车  如果是直接购买则不需要删除购物车
        for (let i = 0; i < this.cartList.length; i++) {
          if (this.cartList[i]?.cart_id) {
            const res = await deleteCart(this.cartList[i].cart_id);
            console.log("删除购物车", res);
          }
        }
        //更新商品库存
        for (let i = 0; i < this.cartList.length; i++) {
          const res = await updateProducts({
            product_id: this.cartList[i].product_id,
            stock: this.cartList[i].stock - this.cartList[i].quantity,
          });
          console.log("更新商品库存", res);
        }
        this.$confirm("已生成订单，确认支付订单吗？, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const data = {
              order_id: res.data.order_id,
              status: 2,
            };
            const res1 = await updateOrders(data);
            console.log("支付", res1);
            if (res1.status === 0) {
              //更新用户余额
              await updateInfo({
                user_id: +this.token,
                money: this.userInfo.money - +this.total,
              });
              this.$message({
                type: "success",
                message: "支付成功!",
              });
              this.$router.push({
                name: "home",
                query: {
                  activeComIndex: "OrderIndex",
                },
              });
              //刷新页面
              this.$router.go(0);
            } else {
              this.$message.error("支付失败！");
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "订单未支付",
            });
            this.$router.push({
              name: "home",
              query: {
                activeComIndex: "OrderIndex",
              },
            });
            //刷新页面
            this.$router.go(0);
          });
      } else {
        this.$message.error("下单失败！");
      }

      // this.title = "待支付";
      //   this.addVisible = true;
      //   this.storeForm = {};
    },

    async changeDefault(row) {
      this.$confirm("确认设置该地址为默认地址吗？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const params = {
            cart_id: row.cart_id,
            user_id: +this.token,
            is_default: 1,
          };
          const res = await updateCart(params);
          if (res.status === 0) {
            this.$message({
              type: "success",
              message: "修改默认地址成功",
            });
            this.getAllCartsByUserId();
          } else {
            this.$message.error("修改失败！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async getAllCartsByUserId() {
      if (!this.token) {
        this.$message.warning("请先登录！");
        return this.$router.push("/login");
      }
      const { data: res } = await getAllCartsByUserId(+this.token);

      this.cartList = res || [];
    },
    addStoreConfirm() {
      //刷新列表
      this.getAllCartsByUserId();
    },
  },
};
</script>

<style scoped lang="scss">
.order-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 50px;

  .el-card {
    padding: 20px;

    .flex-center {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
    }
  }
}

.btn-list {
  display: flex;
  justify-content: center;

  .el-button {
    width: 200px;
  }
}

.product-detail {
  background-color: #fff;
}

.total-price {
  padding: 20px 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-right: 20px;

  .total {
    margin-right: 20px;

    .price {
      color: red;
      font-size: 20px;
    }
  }
}

.el-radio {
  ::v-deep .el-radio__label {
    display: none !important;
  }
}
</style>
